import {defineStore} from "pinia";
import {ref} from "vue";
import {changeArticleCountApi, getArticleInfoApi, getArticleListApi} from "@/api/articleApi.js";

export const useArticleStore = defineStore('articleStore', () => {
    let articleList = ref([]);  // 帖子数据
    let articleTotal = ref(0) // 帖子总条数
    let sort = ref(['推荐', '热度', '日期', '点赞']); // 排序方式
    let activeSort = ref(0) // 激活的排序方式
    let boardId = ref('') // 板块id
    let loading = ref(true) //true 展示加载骨架屏
    let articleCurrentPage = ref(0) // 当前页
    let searchField = ref('')//搜索字段
    /**
     * 获取分页帖子集合
     * @returns {Promise<void>}
     */
    const getArticleList = async (page = 1) => {
        loading.value = true // 初次加载时开启骨架屏
        let response = await getArticleListApi(boardId.value, activeSort.value, page, 10, searchField.value.trim());
        // 追加数据
        response.data.forEach(item => {
            const regExp = new RegExp(searchField.value,'g');
            item.summary = item.summary.replace(regExp,`<span style="color: red">${searchField.value}</span>`)
            item.title = item.title.replace(regExp,`<span style="color: red">${searchField.value}</span>`)
            articleList.value.push(item)
        })
        articleTotal.value = response.dataMap.total
        articleCurrentPage.value = page // 修改当前页
        loading.value = false
    }

    let articleInfo = ref({}) // 帖子详情对象
    /**
     * 获取帖子详情
     * @returns {Promise<void>}
     */
    const getArticleInfo = async (articleId) => {
        let response = await getArticleInfoApi(articleId);
        articleInfo.value = response.data
    }

    /**
     * 帖子点赞
     * @param articleId
     * @returns {Promise<void>}
     */
    const likeArticle = async (articleId) => {
        await changeArticleCountApi(articleId, 1);
    }

    return {
        articleList, sort, activeSort, boardId, articleInfo, loading, articleCurrentPage, articleTotal, searchField,
        getArticleList, getArticleInfo, likeArticle
    }
})